//
//  MineViewController.m
//  AILock
//
//  Created by 谭亚明on 2020/6/17.
//  Copyright © 2020 tym. All rights reserved.
//

#import "MineViewController.h"
#import "TYMBaseTableView.h"
#import "WCQRCodeVC.h"
#import "WXApi.h"
#import "UserService.h"
#import "AboutOurVC.h"
#import "UIButton+Badge.h"
#import "UserMessageService.h"
#import "MessageVC.h"
#import "UIView+ZFFrame.h"
#import "MessageSettingVC.h"
#import "OrderHistoryVC.h"
#import "FamilyManageVC.h"
#import "MineSettingViewController.h"
#import "ShowQRcodeView.h"
#import "MineViewCell.h"
#import "UserTool.h"
#import "AboutOurVC.h"
#import "MagicImageView.h"
#import "UserModel.h"
#import "MineViewBtn.h"
#import "UIButton+ImageTitleSpacing.h"
#import "UIImageView+YPImage.h"
#import "Sizes.h"
#import "EquipmentRepairVC.h"
#import  "RoomManagerVC.h"
#import "FamilyService.h"
@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,copy) NSArray *dataArray;

@property(nonatomic,weak)IBOutlet UIView *conView;
@property(nonatomic,weak)IBOutlet TYMBaseTableView *tableView;

//@property(nonatomic,weak) IBOutlet MagicImageView  *headImage;
@property(nonatomic,weak) IBOutlet UIImageView  *headImage;
@property(nonatomic,weak) IBOutlet UILabel *userNameLab;
@property(nonatomic,weak) IBOutlet UILabel *roleLab;
@property(nonatomic,weak) IBOutlet UILabel *descLab;

@property(nonatomic,weak) IBOutlet UIView *stackView;
@property(nonatomic,weak) IBOutlet MineViewBtn *familyBtn;
@property(nonatomic,weak) IBOutlet MineViewBtn *scanBtn;
@property(nonatomic,weak) IBOutlet MineViewBtn *revampBtn;

@property(nonatomic,strong) FamilyService *service;
@property(nonatomic,strong) UserService *usrService;
@property(nonatomic,strong) UserMessageService *messgeServices;

@property(nonatomic,weak) IBOutlet UIButton *megBtn;
@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
  
    _dataArray = @[@{@"title":@"家庭管理",
                     @"iconName":@"icon_mine_list1"},
                   @{@"title":@"房间管理",
                     @"iconName":@"icon_mine_list2"},
                   @{@"title":@"设备报修",
                     @"iconName":@"icon_mine_list4"},
                   @{@"title":@"订单记录",
                   @"iconName":@"icon_jilu"},
                   @{@"title":@"消息设置",
                   @"iconName":@"icon_xiaoxi"},
                   //@{@"title":@"服务支持",@"iconName":@"icon_mine_list3"},
                     @{@"title":@"关于我们",
                      @"iconName":@"icon_mine_list5"}];

    [self.tableView registerNib:[UINib nibWithNibName:@"MineViewCell" bundle:nil] forCellReuseIdentifier:[MineViewCell identifier]];
    self.headImage.layer.borderColor = [UIColor whiteColor].CGColor;
    self.headImage.layer.borderWidth = 1.5;
    self.conView.zf_width = ScreenWidth - 30;
    self.conView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
    self.conView.layer.cornerRadius = 10;
    self.conView.layer.shadowColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:0.5].CGColor;
    self.conView.layer.shadowOffset = CGSizeMake(0,0);
    self.conView.layer.shadowOpacity = 1;
    self.conView.layer.shadowRadius = 35;
    
    self.stackView.layer.masksToBounds = YES;
    self.stackView.layer.cornerRadius = 5;
    if (self.conView.zf_bottom > ScreenHeight - TabbarHeight) {
        [self.conView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-TabbarHeight - 15);
        }];
    }else{
        self.conView.zf_height = 360;
    }


    TYMWeak(self);
    [self.familyBtn setImageName:@"icon_mine111" title:@"家庭二维码"];
    self.familyBtn.tapMineViewBtnBlock = ^{
        [ShowQRcodeView showQRCodeView];
    };
    [self.scanBtn setImageName:@"icon_mine222" title:@"扫描二维码"];
    self.scanBtn.tapMineViewBtnBlock = ^{
        WCQRCodeVC *codeVC = [[WCQRCodeVC alloc] init];
        [weakself.navigationController pushViewController:codeVC animated:YES];
    };
    [self.revampBtn setImageName:@"icon_mine333" title:@"修改资料"];
    self.revampBtn.tapMineViewBtnBlock = ^{
        MineSettingViewController *settingVC = [[MineSettingViewController alloc] init];
        [weakself.navigationController pushViewController:settingVC animated:YES];
    };
}

-(UserMessageService*)messgeServices{
    if (_messgeServices == nil) {
        _messgeServices = [[UserMessageService alloc] init];
    }
    return _messgeServices;
}

-(UserService*)usrService{
    if (_usrService == nil) {
        _usrService = [[UserService alloc] init];
    }
    return _usrService;
}

-(FamilyService*)service{
    if (_service == nil) {
        _service = [[FamilyService alloc] init];
    }
    return _service;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getCurrentUserFamilyWithWeb];
    [self getUnReadUnmber];
    [self getUpdateUser];
     
    [self.navigationController navigationController:self.navigationController willShowViewController:self animated:YES];
}

-(IBAction)gotoMineSettingAction:(id)sender{
    
    MineSettingViewController *settingVC = [[MineSettingViewController alloc] init];
    [self.navigationController pushViewController:settingVC animated:YES];
}

-(IBAction)messageAction:(id)sender{
    MessageVC *messageVC = [[MessageVC alloc] init];
       [self.navigationController pushViewController:messageVC animated:YES];
}

-(void)updateCurrentUserData{
    
    if ([[UserTool getLogInUser] getEquipmentImage].length) {
        
        self.headImage.userInteractionEnabled = YES;
        [self.headImage yp_setImageUlr:[[UserTool getLogInUser] getEquipmentImage] placeHolder:@"icon_tx2"];
    }else{
        [self.headImage setImage:[UIImage imageNamed:@"icon_tx2"]];
        self.headImage.userInteractionEnabled = NO;
    }
    
    self.roleLab.text = [[UserTool getCurrentFamily] getRoleStr];
    self.descLab.text = @"智能锁保护您的家庭";
    if ([UserTool getLogInUser].nickname) {
        self.userNameLab.text = [UserTool getLogInUser].nickname;
    }else{
        self.userNameLab.text = self.userNameLab.text = [UserTool getLogInUser].mobile;
    }
}

-(void)getUnReadUnmber{
    if ([UserTool getLogInUser] == nil) {
        return;
    }
    TYMWeak(self);
    [self.messgeServices getUnreadnumFamilyId:[UserTool getCurrentFamily].familyId completion:^(LMJBaseResponse *respon) {
        if ([respon.responseObject[@"data"] integerValue] > 0) {
            [weakself.megBtn showRed];
        }else{
            [weakself.megBtn hiddenRed];
        }
    }];
}

-(void)getUpdateUser{
    [self.usrService getFindusercompletion:^(NSError * _Nonnull error, UserModel * _Nonnull response) {
        if (response) {
            [UserTool getLogInUser].nickname = response.nickname;
            [UserTool getLogInUser].headImgUrl = response.headImgUrl;
            
            [self updateCurrentUserData];
        }
    }];
}

-(void)getCurrentUserFamilyWithWeb{
    if([UserTool getLogInUser] == nil){
       return;
    }
    TYMWeak(self);
    [self.service getFamilyUserCurrentCompletion:^(LMJBaseResponse *resp, FamilyModel * _Nonnull response) {
        if (!resp.code) {
            [UserTool setFamily:response completion:^(BOOL state) {
                if(state){
                                  [weakself updateCurrentUserData];
                               }
            }];
        }
    }];
}

#pragma  mark - tableView 代理
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [MineViewCell  cellForHeight];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MineViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[MineViewCell identifier] forIndexPath:indexPath];
    NSDictionary *dataDic = self.dataArray[indexPath.row];
    cell.titleLab.text = dataDic[@"title"];
    [cell.iconImage setImage:[UIImage imageNamed:dataDic[@"iconName"]]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        FamilyManageVC *familyVC = [[FamilyManageVC alloc] init];
        [self.navigationController pushViewController:familyVC animated:YES];
    }else if(indexPath.row == 1){
        RoomManagerVC *roomManagerVC = [[RoomManagerVC alloc] init];
        [self.navigationController pushViewController:roomManagerVC animated:YES];
    }else if(indexPath.row == 2){
        if (![WXApi isWXAppInstalled]) {
            [WHToast showMessage:@"无法调用小程序" duration:2 finishHandler:nil];
            return;
        }
        
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName = @"gh_0299e0221ca8";  //拉起的小程序的username
        launchMiniProgramReq.path = @"/pages/service/service";    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
#ifdef DEBUG
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypePreview; //拉起小程序的类型
#else
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
#endif //拉起小程序的类型
        [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
           
        }];
        
//        EquipmentRepairVC *repairVC = [[EquipmentRepairVC alloc] init];
//        [self.navigationController pushViewController:repairVC animated:YES];
    }else if(indexPath.row == 3){
        if (![WXApi isWXAppInstalled]) {
            [WHToast showMessage:@"无法调用小程序" duration:2 finishHandler:nil];
            return;
        }
        
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName = @"gh_0299e0221ca8";  //拉起的小程序的username
        //launchMiniProgramReq.path = @"";    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
#ifdef DEBUG
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypePreview; //拉起小程序的类型
#else
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
#endif //拉起小程序的类型
        [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
           
        }];
        
        
//        OrderHistoryVC *orderVC = [[OrderHistoryVC alloc] init];
//        [self.navigationController pushViewController:orderVC animated:YES];
    }else if(indexPath.row == 4){
        MessageSettingVC *messageVC = [[MessageSettingVC alloc] init];
        [self.navigationController pushViewController:messageVC animated:YES];
    }else if(indexPath.row == 5){
        
        AboutOurVC *aboutVC = [[AboutOurVC alloc] init];
        [self.navigationController pushViewController:aboutVC  animated:YES];
    }
}


@end
